﻿using System.Collections.Generic;
using EmbeddedSharp.Core;

namespace Zove.Runtime.Core.EquationTransformer
{
    public class RouteFinder
    {
        protected readonly string ObjectiveVariable = string.Empty;

        public RouteFinder(string objectiveVariable)
        {
            ObjectiveVariable = objectiveVariable;
            Route = new Stack<int>();
        }

        public Stack<int> Route { get; set; }

        public bool Visit(Node node)
        {
            if (node.GetType().IsSubclassOf(typeof (OperatorNode)))
            {
                if (Visit(((OperatorNode) node).Left))
                {
                    Route.Push(0);
                    return true;
                }
                if (Visit(((OperatorNode) node).Right))
                {
                    Route.Push(1);
                    return true;
                }
            }
            else if (node.GetType().IsSubclassOf(typeof (FuncNode)))
            {
                var fn = (FuncNode) node;
                for (int index = 0; index < fn.Parameters.Count; index++)
                {
                    if (Visit(fn.Parameters[index]))
                    {
                        Route.Push(index);
                        return true;
                    }
                }
            }
            else if (node.GetType().Equals(typeof (IdentifierNode))
                     || node.GetType().IsSubclassOf(typeof (IdentifierNode))
                )
            {
                if (node.Value == ObjectiveVariable)
                {
                    return true;
                }
            }

            return false;
        }
    }
}